import React, { useState, useEffect } from 'react';
import './StorageManager.css';
import dbStorage from '../utils/dbStorage';

const StorageManager = ({ isVisible, onClose }) => {
  const [storageInfo, setStorageInfo] = useState({ fileCount: 0, totalSize: 0, formattedSize: '0 B' });
  const [cachedFiles, setCachedFiles] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (isVisible) {
      loadStorageInfo();
    }
  }, [isVisible]);

  const loadStorageInfo = async () => {
    setLoading(true);
    try {
      const info = await dbStorage.getStorageInfo();
      setStorageInfo(info);
      
      const files = await dbStorage.getAllFiles();
      setCachedFiles(files);
    } catch (error) {
      console.error('加载存储信息失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteFile = async (fileId) => {
    if (window.confirm('确定要删除这个文件缓存吗？')) {
      try {
        await dbStorage.deleteFile(fileId);
        await loadStorageInfo(); // 重新加载
      } catch (error) {
        console.error('删除文件失败:', error);
        alert('删除文件失败: ' + error.message);
      }
    }
  };

  const handleClearAll = async () => {
    if (window.confirm('确定要清空所有缓存吗？此操作不可撤销！')) {
      try {
        await dbStorage.clearAll();
        await loadStorageInfo(); // 重新加载
        alert('缓存已清空');
      } catch (error) {
        console.error('清空缓存失败:', error);
        alert('清空缓存失败: ' + error.message);
      }
    }
  };

  const handleCleanExpired = async () => {
    try {
      await dbStorage.cleanExpiredData();
      await loadStorageInfo(); // 重新加载
      alert('过期缓存已清理');
    } catch (error) {
      console.error('清理过期缓存失败:', error);
      alert('清理过期缓存失败: ' + error.message);
    }
  };

  const formatDate = (timestamp) => {
    return new Date(timestamp).toLocaleString('zh-CN');
  };

  if (!isVisible) return null;

  return (
    <div className="storage-manager-overlay">
      <div className="storage-manager-modal">
        <div className="storage-header">
          <h3>📦 缓存管理</h3>
          <button className="close-btn" onClick={onClose}>✕</button>
        </div>

        <div className="storage-content">
          {loading ? (
            <div className="loading-state">
              <p>⏳ 加载中...</p>
            </div>
          ) : (
            <>
              <div className="storage-summary">
                <div className="summary-item">
                  <span className="label">文件数量:</span>
                  <span className="value">{storageInfo.fileCount} 个</span>
                </div>
                <div className="summary-item">
                  <span className="label">占用空间:</span>
                  <span className="value">{storageInfo.formattedSize}</span>
                </div>
              </div>

              <div className="storage-actions">
                <button 
                  className="action-btn clean-btn"
                  onClick={handleCleanExpired}
                  title="清理超过7天的缓存"
                >
                  🧹 清理过期
                </button>
                <button 
                  className="action-btn danger-btn"
                  onClick={handleClearAll}
                  title="删除所有缓存文件"
                >
                  🗑️ 清空全部
                </button>
              </div>

              <div className="file-list">
                <h4>缓存文件列表</h4>
                {cachedFiles.length === 0 ? (
                  <div className="empty-state">
                    <p>暂无缓存文件</p>
                  </div>
                ) : (
                  <div className="file-items">
                    {cachedFiles.map(file => (
                      <div key={file.id} className="file-item">
                        <div className="file-info">
                          <div className="file-name">
                            <span className={`file-type ${file.type}`}>
                              {file.type === 'audio' ? '🎵' : '📝'}
                            </span>
                            {file.name}
                          </div>
                          <div className="file-details">
                            <span>{dbStorage.formatFileSize(file.size)}</span>
                            <span>{formatDate(file.timestamp)}</span>
                          </div>
                        </div>
                        <button 
                          className="delete-file-btn"
                          onClick={() => handleDeleteFile(file.id)}
                          title="删除此文件缓存"
                        >
                          🗑️
                        </button>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </>
          )}
        </div>

        <div className="storage-footer">
          <div className="storage-tips">
            <p>💡 提示: 缓存文件可以在移动端后台切换时快速恢复播放状态</p>
            <p>🕒 自动清理: 超过7天的缓存会自动删除</p>
          </div>
        </div>
      </div>
    </div>
  );
};

export default StorageManager;